
/**
 * 压缩图片
 * @param {file} file 文件file
 * @param {string} filename filename 为name   
 * @param {object} objCompressed objCompressed 可传图片宽高,高默认同比例
 * @returns 
 */
export function compressImgs(file, objCompressed = {}) {
    return new Promise((resolve, reject) => {
        const windowURL = window.URL || window.webkitURL;
        const src = windowURL.createObjectURL(file);
        var img = new Image()
        img.src = src

        img.onload = function () {
            var that = this
            //默认压缩后图片规格
            var quality = 0.7
            var wd = that.width
            var hd = that.height
            var scale = wd / hd
            //实际要求
            const w = objCompressed.width || wd
            const h = objCompressed.height || w / scale
            //生成canvas
            var canvas = document.createElement('canvas')
            var ctx = canvas.getContext('2d')
            // 创建属性节点
            var anw = document.createAttribute('width')
            anw.nodeValue = w
            var anh = document.createAttribute('height')
            anh.nodeValue = h
            canvas.setAttributeNode(anw)
            canvas.setAttributeNode(anh)
            ctx.drawImage(that, 0, 0, w, h)
            var base64 = canvas.toDataURL('image/jpeg', quality)
            const url = dataURLtoFile(base64, file.name)
            // 回调函数返回base64的值
            resolve(url)
        }
    })
}
export function dataURLtoFile(dataurl, filename = Date.now()) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    // var url = URL || webkitURL
    // return url.createObjectURL(new Blob([u8arr], { type: mime }))
    return new File([u8arr], filename, {
        type: mime
    })
}

export const download = (res, ssq, name) => {
    // 创建blob对象，解析流数据
    const blob = new Blob([res], {
        // 如果后端没返回下载文件类型，则需要手动设置：type: 'application/pdf;chartset=UTF-8' 表示下载文档为pdf，如果是word则设置为'application/msword'，zip为 'application/zip'
        type: res.type
    })

    const a = document.createElement('a')
    // 兼容webkix浏览器，处理webkit浏览器中href自动添加blob前缀，默认在浏览器打开而不是下载
    const URL = window.URL || window.webkitURL
    // 根据解析后的blob对象创建URL 对象
    const herf = URL.createObjectURL(blob)
    // 下载链接
    a.href = herf
    // 下载文件名,如果后端没有返回，可以自己写a.download = '文件.pdf'
    a.download = name + ssq
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    // 在内存中移除URL 对象
    window.URL.revokeObjectURL(herf)
}
